from fastapi import APIRouter, Query
from tortoise.expressions import Q

from fastapiApp.controllers.api_control import api_controller
from fastapiApp.schemas.base_scheams import Success, SuccessExtra, Fail
from fastapiApp.schemas.api_scheams import *

router = APIRouter()


@router.get("/get_list", summary="查看API列表")
async def list_api(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    path: str = Query("", description="API路径"),
    summary: str = Query("", description="API简介"),
    tags: str = Query("", description="API模块")
):
    total, data = await api_controller.list(page=page, page_size=page_size, path=path, summary=summary, tags=tags)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@router.get("/get_info", summary="查看Api")
async def get_api(
    id: int = Query(..., description="Api")
):
    api_obj = await api_controller.model.get(id=id)
    data = await api_obj.to_dict()
    return Success(data=data)

@router.post("/create", summary="创建Api")
async def create_api(
    obj_in: ApiCreate
):
    await api_controller.is_exist(obj_in = obj_in)
    await api_controller.model.create(** obj_in.model_dump())
    return Success(msg="Created Successfully")

@router.post("/update", summary="更新Api")
async def update_api(
    obj_in: ApiUpdate
):
    await api_controller.update_api(obj_in=obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")

@router.delete("/delete", summary="删除Api")
async def delete_api(
    id: int = Query(..., description="ApiID")
):
    api = await api_controller.model.get_or_none(id = id)
    if api:
        await api.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")

@router.post("/refresh", summary="刷新API列表")
async def refresh_api():
    await api_controller.refresh_api()
    return Success(msg="OK")
